<!--
 * @Description: 博客详情页
 * @Author: 梁晓雨
 * @Date: 2025-02-10 01:29:01
-->
<template>
    <div class="main-content">
        <div class="top-bar">
            <div class="userinfo" style="display: none;">
                <el-avatar :size="50" />
                <div class="username-email">
                    <el-text class="fullWid username">
                        用户名
                    </el-text>
                    <el-text class="fullWid email" type="info">
                        2662258652@qq.com
                    </el-text>
                </div>
            </div>

        </div>
        <div class="catalogue">
            <el-avatar :src="datas.blogPhotoSrc" class="blog-avatar" />
            <el-text class="catalogueName">{{ datas.directoryName }}</el-text>
            <el-text class="blogUpdated">{{ datas.blogUpdated }}</el-text>
            <el-text class="fixed-text">最后修改</el-text>
        </div>
        <div class="relay-content">
            <el-text> {{ datas.relayContent }} </el-text>
        </div>
        <div class="blog-item-card">

            <div class="blog-item-card-content">
                <div class="blogTitle">
                    <el-text>{{ datas.blogTitle }}</el-text>
                </div>
                <div class="blog-item-card-tags">
                    <el-tag round v-for="item in datas.tagName" :key="item" type="success">{{ item }}</el-tag>
                </div>
                <div class="blog-item-card-AIsummary">
                    <el-text>{{ datas.aiSummary }}</el-text>
                </div>
                <div class="blogText">
                    <div v-html="datas.blogText"></div>
                </div>
            </div>

        </div>
        <div class="blog-item-comment-button">
            <el-button type="danger" @click="toDelete" v-if="deleteButtonStatus">删除</el-button>
            <el-button type="info" @click="toShare">分享</el-button>
            <el-button type="warning" @click="toRelay">转发</el-button>
            <el-button type="primary" @click="toEdit" v-if="editButtonStatus">编辑</el-button>
            <el-button type="primary" @click="toComment">评论</el-button>
        </div>
        <el-divider></el-divider>
        <div class="comment-layout">
            <!-- <el-affix :offset="80" position="top" target=".comment-layout">
                <el-card>
                    <el-input placeholder="@博主" v-model="valueComment" style="width: 500px;"></el-input>
                    <el-button type="warning" @click="toComment" class="comment-button">评论</el-button>
                </el-card>
            </el-affix> -->

            <div class="comment-section">
                <div v-for="(comment, index) in testCommentData" :key="index">
                    <CommentItem :comment="comment" @refresh="toRefresh" />
                </div>
            </div>

        </div>
    </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import CommentItem from "../../../../components/CommentItem/CommentItem.vue";
import request from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import StringtoStrArray from '@/utils/StringtoStrArray';
import StringtoNumArray from '@/utils/StringtoNumArray';
import store from '@/store';
import router from '@/router';
import { data } from 'dom7';

const route = useRoute();

// 从url中获取查询参数
const userid = Number(route.query.userid);
const blogid = Number(route.query.blogid);

// 标签信息
interface Tag {
    label: String,
    type: String
}
// 博客详情
interface Data {
    blogid: number,
    userid: number,
    blogTitle: string,
    aiSummary: string,
    blogText: string,
    blogPhotoSrc: string,
    directoryId: number,
    directoryName: string,
    directorySrc: string,
    blogUpdated: string,
    tagId: Array<number>,
    tagName: Array<string>,
    relayContent: string,
    originalBlogId: number,
    isDeletedBlog: number,
}
// 创建空博客对象的工具函数
const createEmptyBlog = (): Data => {
    return {
        blogid: 0,
        userid: 0,
        blogTitle: '',
        aiSummary: '',
        blogText: '',
        blogPhotoSrc: '',
        directoryId: 0,
        directoryName: '',
        directorySrc: '',
        blogUpdated: '',
        tagId: [],
        tagName: [],
        relayContent: '',
        originalBlogId: 0,
        isDeletedBlog: 0,
    };
};
// 博客详情数据
const datas = ref<Data>(createEmptyBlog())
// 评论输入框绑定值
const valueComment = ref('')
// 评论
interface Comment {
    commentid: number,
    blogid: number,
    useridComment: number,
    usernameComment: string,
    parentid: number,
    username: string,
    content: string,
    children?: Comment[]
}
// 评论数据
const testCommentData = ref<Comment[]>([])
// 删除按钮的显示状态
const deleteButtonStatus = ref(false)
// 编辑按钮的显示状态
const editButtonStatus = ref(false)



// 增加评论
const toComment = async () => {
    const username = store.getters.getUser.username;
    ElMessageBox.prompt('评论内容', '评论', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
    })
        .then(async ({ value }) => {
            await request.post('/comment/add', {
                commentid: null,
                blogid: blogid,
                useridComment: userid,
                usernameComment: username,
                parentid: -1,
                content: value,
                isDeletedComment: 0,
                children: null
            })
                .then(async res => {
                    await toRefresh();
                    ElMessage({
                        type: 'success',
                        message: '评论成功'
                    })
                })
                .catch(error => {
                    ElMessage({
                        type: 'error',
                        message: '评论失败'
                    })
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消评论'
            })
        })
}




/**
 * @description: 获取博客详情
 * @Author: 梁晓雨
 * @Date: 2025-03-05 21:45:13
 */
const getBlogDetail = async () => {

    try {
        await request.get('/blog/queryAll', {
            params: {
                // userid: userid,
                blogid: blogid
            }
        }).then(res => {
            console.log(res.data);


            res.data[0].tagName = StringtoStrArray(res.data[0].tagName)
            res.data[0].tagId = StringtoNumArray(res.data[0].tagId)

            datas.value = res.data[0]
        })
    } catch (error) {
        ElMessage({
            message: '获取博客详情失败，请刷新重试',
            type: 'error'
        })
    }

}
/**
 * @description: 获取评论详情
 * @Author: 梁晓雨
 * @Date: 2025-03-09 21:04:21
 */
const getCommentDetail = async () => {
    try {
        await request.get('/comment/queryAll', {
            params: {
                blogid: blogid
            }
        })
            .then(res => {
                testCommentData.value = res.data;
            })
    } catch (error) {
        ElMessage({
            message: "评论获取出错",
            type: "error"
        })
    }
}
/**
 * @description: 刷新评论区
 * @Author: 梁晓雨
 * @Date: 2025-03-10 18:48:42
 */
const toRefresh = async () => {
    await request.get('/comment/queryAll', {
        params: {
            blogid: blogid
        }
    })
        .then(res => {
            testCommentData.value = res.data;
        })
}

/**
 * @description: 转发当前博文
 * @Author: 梁晓雨
 * @Date: 2025-03-10 20:32:56
 */
const toRelay = async () => {
    try {
        ElMessageBox.prompt('转发博文的配文', '转发博文', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
        })
            .then(async ({ value }) => {
                // 新增转发型博文，value是转发配文
                const currentTime = new Date().toLocaleString();
                await request.post('/blog/add', {
                    blogid: null,
                    userid: userid,
                    blogTitle: null,
                    aiSummary: null,
                    blogText: value,
                    blogPhotoSrc: null,
                    directoryId: null,
                    directoryName: null,
                    directorySrc: null,
                    blogUpdated: currentTime,
                    tagId: null,
                    tagName: null,
                    originalBlogId: blogid,
                    isDeletedBlog: 0
                })

                ElMessage({
                    type: 'success',
                    message: '转发成功'
                })

            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消转发'
                })
            })
    } catch (error) {
        ElMessage({
            message: '转发失败',
            type: 'error'
        })
    }
}


/**
 * @description: 分享当前博文
 * @Author: 梁晓雨
 * @Date: 2025-03-11 18:23:07
 */
const toShare = async () => {
    const fullUrl = window.location.href;

    navigator.clipboard.writeText(fullUrl)
        .then(() => {
            ElMessage({
                type: 'success',
                message: '复制成功'
            })
        })
        .catch((err) => {
            ElMessage({
                type: 'success',
                message: err
            })
        })
}

/**
 * @description: 删除当前博文
 * @Author: 梁晓雨
 * @Date: 2025-03-17 15:26:13
 */
const toDelete = async () => {
    try {
        ElMessageBox.confirm(
            '您确定要删除当前博文吗？',
            '注意',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
            .then(async () => {
                await request.delete('/blog/deleteById', {
                    params: {
                        id: blogid
                    }
                })
                    .then(() => {
                        ElMessage({
                            type: 'success',
                            message: '删除成功'
                        })
                    })
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消删除'
                })
            })
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '删除失败'
        })
    }
}

/**
 * @description: 编辑当前博文，默认为富文本编辑器
 * @Author: 梁晓雨
 * @Date: 2025-03-17 15:26:46
 */
const toEdit = async () => {
    //edit
    ElMessageBox.confirm(
        '是否跳转到编辑页面？',
        '注意',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
        .then(() => {
            router.push({
                name: 'blogMainDetailEdit',
                query: {
                    datas: JSON.stringify(datas.value) // 转换为 JSON 字符串
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消编辑'
            })
        })
}

/**
 * @description: 初始化时，决定“删除”按钮的显示状态。只有用户本人或者超级管理员才能删除博文
 * @Author: 梁晓雨
 * @Date: 2025-03-17 16:35:44
 */
const determineDeleteButtonStatus = async() => {

    // 当博文发布者是用户本人时
    const useridCurrent = store.getters.getUser.userId;
    if(useridCurrent == datas.value.userid){
        deleteButtonStatus.value = true;
    }else{
        console.log("非用户本人的博文");
        console.log(useridCurrent);
        console.log(datas.value.userid);
        
        
    }
    // 当用户本人是超级管理员时
    try {
        await request.get(`user/${useridCurrent}`)
        .then(res => {
            if(res.data.rights == 'AD'){
                deleteButtonStatus.value = true;
            }
        })
    } catch (error) {
        ElMessage({
            type:'error',
            message:'获取用户权限出错'
        })
    }
}

/**
 * @description:初始化时，决定“编辑”按钮的显示状态。只有用户本人才能编辑博文
 * @Author: 梁晓雨
 * @Date: 2025-03-17 16:36:35
 */
const determineEditButtonStatus = () => {
    const useridCurrent = store.getters.getUser.userId;

    if (useridCurrent == datas.value.userid) {
        editButtonStatus.value = true;
    } else {
        editButtonStatus.value = false;
    }
}



// 初始化
onMounted(
    async () => {
        
        await getBlogDetail();
        await getCommentDetail();
        determineDeleteButtonStatus();
        determineEditButtonStatus();

    }
)
</script>
<style lang="scss" scoped>
@use './BlogMainDetail.scss';
</style>
